﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Admin_Web_test.Models;
using Common.DBHelp;
using Common.Utility;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Internal;
using Model;
using MySql.Data.MySqlClient;

namespace Admin_Web_test.Controllers
{
    public class ShopController : Controller
    {
        private readonly Common.DBHelp.MySqlContext _context;

        public ShopController(Common.DBHelp.MySqlContext context)
        {
            //https://www.cnblogs.com/yaopengfei/p/12194230.html   5.6
            context.ChangeTracker.QueryTrackingBehavior = Microsoft.EntityFrameworkCore.QueryTrackingBehavior.NoTracking;
            //关闭状态同步
            context.ChangeTracker.AutoDetectChangesEnabled = false;
            //开启：context.ChangeTracker.DetectChanges();
            _context = context;
        }
        [PowerActionFilter]
        public IActionResult Commodity()
        {
            return View();
        }
        // 商品列表
        [PowerActionFilter]
        public JsonResult CommodityList(int page=0,int limit =0,int big=0,int centre=0,int little=0,string shopName="")
        {
            string sql = @"select a.id,a.`Name`,a.Image,a.Type,b.`Name` as typeName,a.Price,a.ShopNum,a.Comment,a.`Remark` 
                                 from `commodity` a inner join ";
            string sqlcount = @"select count(1) 
                                 from `commodity` a inner join ";
            List<MySqlParameter> para = new List<MySqlParameter>();
            if (big == 0)
            {
                sql += " `type` ";
                sqlcount += " `type` ";
            }
            else if (centre == 0) {
                sql += " (select Id,`Name` from `type` where Id in (select Id from `type` where ParentId in (select Id from `type` where ParentId=@type))) ";
                sqlcount += " (select Id,`Name` from `type` where Id in (select Id from `type` where ParentId in (select Id from `type` where ParentId=@type))) ";
                para.Add(new MySqlParameter("@type", big));
            }
            else if (little == 0) {
                sql += " (select  Id,`Name`  from `type` where Id in (select Id from `type` where ParentId=@type)) ";
                sqlcount += " (select  Id,`Name`  from `type` where Id in (select Id from `type` where ParentId=@type)) ";
                para.Add(new MySqlParameter("@type", centre));
            }
            else {
                sql += " (select Id,`Name` from type where Id=@type) ";
                sqlcount += " (select Id,`Name` from type where Id=@type) ";
                para.Add(new MySqlParameter("@type", little));
            }
            sql += " b on a.Type=b.Id   ";
            sqlcount += " b on a.Type=b.Id   ";
            if (!string.IsNullOrWhiteSpace(shopName))
            { 
                sql += " where a.`Name` like @name ";
                sqlcount += " where a.`Name` like @name ;";
                para.Add(new MySqlParameter("@name", "%"+shopName.Trim()+"%"));
            }
            sql += " limit "+(page-1)*limit+","+limit+";";
            DataTable dt = _context.Database.SqlQuery(sql, para.ToArray());
            //DataTable newDT = dt.Copy();
            //newDT.Clear();
            //int rowbegin = (page - 1) * 10;
            //int rowend = limit * page;
            //if (rowend > dt.Rows.Count) rowend = dt.Rows.Count;
            //if(rowbegin<dt.Rows.Count)
            //{ 
            //    for (int i = rowbegin; i < rowend; i++)
            //    {
            //        DataRow newdr = newDT.NewRow();
            //        DataRow dr = dt.Rows[i];
            //        foreach (DataColumn column in dt.Columns)
            //        {
            //            newdr[column.ColumnName] = dr[column.ColumnName];
            //        }
            //        newDT.Rows.Add(newdr);
            //    }
            //}
            var json = new JsonResultM
            {
                code = 0,
                msg = "",
                count = _context.Database.SqlQuery(sqlcount, para.ToArray()).Rows[0][0].ToString().ToInt(),
                data = dt
            };

            return Json(json);
        }
        // 商品分类   
        public JsonResult CommodityType()
        {
            var json = new JsonResultM();
            var type = _context.Type.ToList();
            var mo = new List<Model.Type>();
            foreach (Model.Type t in type.Where(x=>x.ParentId==0))
            {
                int id = t.Id;
                mo.Add(t);
                foreach (Model.Type t1 in type.Where(x => x.ParentId == id))
                {
                    int pid = t1.Id;
                    mo.Add(t1);
                    foreach (Model.Type t2 in type.Where(x => x.ParentId == pid))
                    {
                        mo.Add(t2);
                    }
                }
            }
            json.data = mo;
            json.code = 0;
            json.msg = "ok";
            json.count = type.Count;
            return Json(json);
        }
        [PowerActionFilter]
        //添加商品
        public JsonResult CommodityAdd(Commodity commodity, string base64Str="")
        {
            var json = new JsonResultM();
            if (string.IsNullOrWhiteSpace(commodity.Name) || string.IsNullOrWhiteSpace(base64Str))
            {
                json.msg = "不能为空";
                return Json(json);
            }
            if (commodity.Type <= 0 || commodity.Price <= 0)
            {
                json.msg = "不能小于0";
                return Json(json);
            }
            commodity.ShopNum = 0;
            commodity.Comment = 0;
            if (_context.Commodity.FirstOrDefault(x => x.Name == commodity.Name) != null)
            {
                json.msg = "已存在该名称的分类。";
                return Json(json);
            }
            string proname = RandomTools.RndLetter(4) + DateTime.Now.ToString("yyyyMMddHHmmssfff");
            proname = $"/Upload/Images/{proname}.png";
            commodity.Image = proname;
            _context.Commodity.AddRange(commodity);
            if (_context.SaveChanges() > 0)
            {
                string path = $"{Directory.GetCurrentDirectory()}//wwwroot/{proname}";
                string filepath = Path.GetDirectoryName(path);
                // 如果不存在就创建file文件夹
                if (!Directory.Exists(filepath))
                {
                    if (filepath != null) Directory.CreateDirectory(filepath);
                }
                var match = Regex.Match(base64Str, "data:image/png;base64,([\\w\\W]*)$");
                if (match.Success)
                {
                    base64Str = match.Groups[1].Value;
                }
                var photoBytes = Convert.FromBase64String(base64Str);
                System.IO.File.WriteAllBytes(path, photoBytes);


                json.success = true;
                json.msg = "成功";
            }
            return Json(json);
        }
        [PowerActionFilter]
        //删除商品
        public JsonResult CommodityDelete(string Id)
        {
            var json = new JsonResultM();
            var arrId = Id.Split(',').ToArray();
            if (arrId.Length <= 0) return Json(json);
            foreach (string d in arrId)
            {
                var remove = _context.Commodity.Where(x => x.Id == d.ToInt());
                _context.Commodity.RemoveRange(remove);
            }
            _context.SaveChanges();
            json.success = true;
            json.msg = "成功";
            return Json(json);
        }
        [PowerActionFilter]
        //更新商品
        public JsonResult CommodityUpdate(Commodity commodity,string base64Str="")
        {
            var json = new JsonResultM();

            if (commodity.Type <= 0 || commodity.Price <= 0)
            {
                json.msg = "不能小于0";
                return Json(json);
            }
            if (string.IsNullOrWhiteSpace(commodity.Name))
            {
                json.msg = "不能为空";
                return Json(json);
            }
            string proname = RandomTools.RndLetter(4) + DateTime.Now.ToString("yyyyMMddHHmmssfff");
            proname = $"/Upload/Images/{proname}.png";
            if (!string.IsNullOrWhiteSpace(base64Str)) commodity.Image = proname;
            _context.Commodity.Update(commodity);
            if (_context.SaveChanges() > 0)
            {
                if (!string.IsNullOrWhiteSpace(base64Str))
                {
                    string path = $"{Directory.GetCurrentDirectory()}//wwwroot/{proname}";
                    string filepath = Path.GetDirectoryName(path);
                    // 如果不存在就创建file文件夹
                    if (!Directory.Exists(filepath))
                    {
                        if (filepath != null) Directory.CreateDirectory(filepath);
                    }
                    var match = Regex.Match(base64Str, "data:image/png;base64,([\\w\\W]*)$");
                    if (match.Success)
                    {
                        base64Str = match.Groups[1].Value;
                    }
                    var photoBytes = Convert.FromBase64String(base64Str);
                    System.IO.File.WriteAllBytes(path, photoBytes);
                }

                json.success = true;
                json.msg = "成功";
            }
            return Json(json);
        }
        [PowerActionFilter]
        public IActionResult CommodityTypeV()
        {
            return View();
        }
        [PowerActionFilter]
        public JsonResult CommodityTypeAddOrUpdate(int rad = 0, int id = 0, string typeName = "", int big = 0, int centre = 0, string actionType = "")
        {
            var json = new JsonResultM();
            if (rad <= 0 || string.IsNullOrWhiteSpace(typeName))
            {
                json.msg = "错误";
                return Json(json);
            }
            if (rad == 2 && big == 0) return Json(json);
            if (rad == 3 && (big == 0|| centre==0)) return Json(json);
            Model.Type type = new Model.Type();
            type.Name = typeName;
            if (rad == 1) type.ParentId = 0;
            else if (rad == 2) type.ParentId = big;
            else type.ParentId = centre;
            if (actionType == "add")
            {
                if (id != 0) return Json(json);
                if (_context.Type.FirstOrDefault(x => x.Name == typeName) != null)
                {
                    json.msg = "已存在该名称的分类。";
                    return Json(json);
                }
                _context.Type.Add(type);
            }
            else if (actionType == "update")
            {
                type.Id = id;
                _context.Type.Update(type);
            }
            _context.SaveChanges();
            json.msg = "成功";
            json.success = true;
            return Json(json);
        }

        [PowerActionFilter]
        public JsonResult CommodityTypeDelete(int id)
        {
            var json = new JsonResultM();
            if (id > 0) _context.Type.Remove(_context.Type.Single(x => x.Id == id));
            else json.msg = "错误";
            if (_context.SaveChanges() > 0) {
                json.msg = "成功";
                json.success = true;
            }
            return Json(json);
        }
    }
}